package com.air.admin.interceptor;


import java.util.ArrayList;
import java.util.List;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.air.common.util.BasicAppConstant;

import com.air.common.util.BasicErrorCode;
import com.air.common.util.WebUtil;
import com.air.common.vo.ResponseVO;




public class AdminLoginInterceptor extends HandlerInterceptorAdapter {
	
	private List<String> needSessionUrl; 
	private List<String> noNeedSessionUrl;  //Higher Priority
		
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	
	
	public void setNeedSessionUrl(List<String> needSessionUrl) {
		this.needSessionUrl = needSessionUrl;
		
	}
	public void setNoNeedSessionUrl(List<String> noNeedSessionUrl) {
		this.noNeedSessionUrl = noNeedSessionUrl;
		
	}
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
			Object handler)	throws Exception {
		
		if (this.needSessionUrl==null){
			this.needSessionUrl = new ArrayList<String>();
		}
		if (this.noNeedSessionUrl==null){
			this.noNeedSessionUrl = new ArrayList<String>();
		}
		
		boolean needLogin = false;
		String requestUrl = request.getRequestURL().toString();
		boolean isAnsyCalling = WebUtil.isAnsyCalling(request);
		
		String requestParamers = WebUtil.parseRequestParamenter2String(request);
		if (request.getQueryString()!=null){
			requestUrl += "?"+new String(request.getQueryString().getBytes("ISO8859_1"),"GBK");
			requestUrl += "&"+requestParamers;
		}else{
			requestUrl += "?"+requestParamers;
		}
		
		if (request.getSession().getAttribute(BasicAppConstant._KEY_ADMIN_SESSION)==null){
			for (String pattern : noNeedSessionUrl){
				if (requestUrl.matches(pattern)){
					return true;
				}
			}
			for (String pattern : needSessionUrl){
				if (requestUrl.matches(pattern)){
					needLogin  = true;
					break;
				}
			}
		}
		
		if (!needLogin){
			return true;
		}
		logger.debug("ADMIN_URL: ["+requestUrl+"],Need Login");
		ResponseVO responseVO = new ResponseVO();
		responseVO.setExecuteResult(false);
		responseVO.setErrCode(BasicErrorCode._ACCESS_CODE_NEED_LOGIN);
		//responseVO.addObject(BasicAppConstant._KEY_LOGIN_RETURN_URL, requestUrl);
		
		request.setAttribute(BasicAppConstant._KEY_RESPONSE_VO, responseVO.toJsonFormat());
		if (isAnsyCalling){
			request.getRequestDispatcher(BasicAppConstant._URI_COMMON_JSON).forward(request, response);
		}else{
			request.getRequestDispatcher(BasicAppConstant._URI_ADMIN_LOGIN).forward(request, response);
		}
		return false;
		
		
	}
	
	
	
}
